package com.lagou.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author srh
 * @date 2020/05/04
 **/
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(String.format("requestUri: %s", request.getRequestURI()));

        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        if (Objects.isNull(username)) {
            response.sendRedirect(request.getContextPath() + "/login/toLogin");
            return false;
        }
        return true;
    }
}
